<route lang="json5" type="home">
{
  style: {
    navigationBarTitleText: '我的小组',
    navigationStyle: 'custom',
    // #ifdef MP-ALIPAY
    enablePullDownRefresh: false,
    'mp-alipay': {
      allowsBounceVertical: 'NO',
      transparentTitle: 'always',
      titlePenetrate: 'YES',
      defaultTitle: '',
    },
    // #endif
  },
}
</route>
<template>
  <CustomNavbar v-model:group-list="groupList" />
  <scroll-view
    :scroll-top="scrollTop"
    :scroll-y="true"
    class="scroll-Y"
    refresher-enabled
    :refresher-triggered="isTriggered"
    @refresherrefresh="upper"
    @scrolltolower="lower"
  >
    <view class="container">
      <uni-collapse accordion>
        <uni-collapse-item
          v-for="(group, groupIndex) in groupList"
          :key="group.id"
          :title="group.groupName + (group.masterUserId == userId ? ' (组长)' : '')"
          :thumb="group.groupAvatar"
        >
          <view class="option">
            <button hover-class="button-active" @tap="shareGroup(group.id)">
              <image
                style="width: 50rpx; height: 50rpx"
                src="@/static/global/qrcode.png"
                mode="scaleToFill"
              />
              邀请码
            </button>
          </view>
          <view class="content" v-for="(member, index) in group.memberList" :key="member.id">
            <image :src="member.avatar" mode="scaleToFill" />
            <text class="text">
              {{ member.nickname }}
            </text>
            <text class="text2">
              {{ member.userId == group.masterUserId ? '(组长)' : '' }}
              <text v-if="member.status == 0">{{ ' (申请) ' }}</text>
              <text v-if="member.userId === userId">{{ '(我)' }}</text>
            </text>
            <view class="del">
              <view>
                <uni-icons
                  v-if="group.masterUserId == userId && member.status == 0"
                  type="checkmarkempty"
                  size="15"
                  @click="approveMember(member)"
                />
              </view>

              <view>
                <uni-icons
                  v-if="group.masterUserId == userId || member.userId === userId"
                  type="closeempty"
                  size="15"
                  @click="delMember(index, group.memberList, groupIndex, groupList)"
                />
              </view>
            </view>
          </view>
        </uni-collapse-item>
      </uni-collapse>
    </view>
    <NullView
      v-if="!groupList || groupList.length == 0"
      content="未参加小组"
      href="去加入~"
      url="/pages/group/join"
    ></NullView>
  </scroll-view>
</template>

<script lang="ts" setup>
import { useUserStore } from '@/store'
import CustomNavbar from './components/CustomNavbar.vue'
import { useGroupStore } from '@/store/group'
import { Group } from '@/types/group'
import { myGroupListApi, groupProcessApi, deleteOrQuiteApi } from '@/service/group'
import NullView from '@/components/NullView.vue'
import { getEnvBaseUrl } from '@/utils'
import { SearchTypeEnum } from '@/enums/SearchTypeEnum'

const groupList = ref<Group[]>([])

const userRef = useUserStore()
const userInfo = userRef.userInfo
const userId = userInfo.id

const groupRef = useGroupStore()
const baseUrl = getEnvBaseUrl()

const shareGroup = async (groupId: number) => {
  uni.showLoading({ title: '生成中,请稍后...', mask: true })
  const paramObj = { pagePath: 'pages/group/join', scene: 'id=' + groupId }
  const avatarRes = await uni.downloadFile({
    url:
      baseUrl +
      '/file/download?type=' +
      SearchTypeEnum.GROUP_SHARE +
      '&param=' +
      JSON.stringify(paramObj), // 仅为示例，并非真实的资源
    header: {
      Authorization: userInfo.token,
    },
  })
  console.log(avatarRes)
  await wx.showShareImageMenu({
    path: avatarRes.tempFilePath,
  })
  uni.hideLoading()
}

onLoad(async () => {
  if (!userRef.isLogined) {
    uni.navigateTo({ url: '/pages/login/login?page=bookshelf' })
    return
  }
  const groupListRes = await myGroupListApi({ page: 1, size: 10 })
  groupRef.groupList = groupListRes.data.records
  console.log('groupRef.groupList', groupRef.groupList)
  groupList.value = groupRef.groupList
})

onShow(() => {
  if (!userRef.isLogined) {
    uni.navigateTo({ url: '/pages/login/login?page=bookshelf' })
  }
})

const approveMember = async (member) => {
  // 添加成员API
  await groupProcessApi({ id: member.id, status: 1 })
  member.status = 1
  uni.showToast({
    title: member.nickname + '已成功进组',
  })
}

const delMember = (index: number, members: any, groupIndex: number, groupList: any) => {
  const member = members[index]
  const group = groupList[groupIndex]
  if (member.status === 0) {
    uni.showModal({
      content: '拒绝' + member.nickname + '进组?',
      success: async (success) => {
        if (success.confirm) {
          // 调用api 退出该组
          await groupProcessApi({ id: member.id, status: 2 })
          uni.showToast({ icon: 'none', title: '拒绝进组成功' })
          members.splice(index, 1)
        }
      },
    })
    return
  }
  if (group.masterUserId === userId) {
    if (member.userId === userId) {
      uni.showModal({
        content: '确定退出该组？',
        success: async (success) => {
          if (success.confirm) {
            // 调用api 退出该组
            await deleteOrQuiteApi({ groupId: group.id, memberId: member.userId })
            uni.showToast({ icon: 'none', title: '退出成功' })
            groupList.splice(groupIndex, 1)
          }
        },
      })
    } else {
      uni.showModal({
        content: '确认删除该组员？',
        success: async (success) => {
          if (success.confirm) {
            // 调用api 删除组员
            await deleteOrQuiteApi({ groupId: group.id, memberId: member.userId })
            uni.showToast({ icon: 'none', title: '删除成功' })
            members.splice(index, 1)
          }
        },
      })
    }
  }
}

const scrollTop = ref(0)
// 触发下拉刷新
const upper = async () => {
  console.log('下拉刷新')
  isTriggered.value = true
  // 加载数据 api 要加 await
  // ...

  const groupListRes = await myGroupListApi({ page: 1, size: 10 })
  groupRef.groupList = groupListRes.data.records
  console.log('groupRef.groupList', groupRef.groupList)
  groupList.value = groupRef.groupList
  setInterval(() => {
    isTriggered.value = false
  }, 1000)
}
const isTriggered = ref(false)

const lower = () => {
  console.log('lower')
  // guessRef.value?.getMore()
}
</script>

<style lang="scss">
.container {
  position: relative;
  padding: 10rpx;
}
.option {
  width: 100%;
  padding: 10 50rpx;
  > button {
    position: relative;
    width: 50%;
    font-size: 30rpx;
    color: #fff;
    background-color: $main-color-low;
  }
  .button-active {
    background-color: $main-color; /* 点击时的背景颜色 */
  }
}
.content {
  position: relative;
  display: flex;
  flex-direction: row;
  justify-content: start;
  width: 95%;
  padding: 15px;

  image {
    width: 60rpx;
    height: 60rpx;
    margin-left: 50rpx;
    border-radius: 50%;
  }

  .text {
    margin-left: 20rpx;
    font-size: 14px;
    line-height: 20px;
    color: #666;
  }
  .text2 {
    margin-left: 10rpx;
    font-size: 12px;
    font-weight: 600;
    line-height: 20px;
    color: $main-color;
  }
  .del {
    position: absolute;
    right: 100rpx;

    view {
      display: inline;
      width: 80rpx;
      height: 80rpx;
      margin: 0 25rpx;
      line-height: 80rpx;
      // background-color: $main-color;
      text-align: center;
      border-radius: 50%;
    }
  }
}

.scroll-Y {
  width: 100%;
  height: calc(100vh - var(--window-top));
}
</style>
